package com.wkr.order.exception;

import com.dianping.cat.Cat;
import com.wkr.common.AppException;
import com.wkr.common.CommonResponse;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class CustomExceptionHandler {

    @ExceptionHandler(AppException.class)
    public CommonResponse<Object> handle(AppException exception) {
        Cat.logError(exception.getExeMsg(), exception);
        try {
            // seata如果事务已经结束 xid会被清除
            // RootContext 底层默认基于threadlocal实现
            if (StringUtils.isNotEmpty(RootContext.getXID())){
                GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            }
        } catch (TransactionException e) {
            log.error(e.getMessage(), e);
            Cat.logError(e.getMessage(), e);
        }
        return CommonResponse.fail("-1", "系统异常");
    }
}
